package com.haojin.java1;

import org.junit.Test;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;

/**
 * @author .29.
 * @create 2022-04-17 9:52
 */
/*
实现TCP的网络编程
例子1：客户端发送信息给服务端，服务端发送信息到控制台
 */
public class TCPTest1 {
    //客户端
    @Test
    public void client(){
        Socket socket = null;
        OutputStream ops = null;
        try {
            InetAddress byName = InetAddress.getLocalHost();
            socket = new Socket(byName, 8899);

            ops = socket.getOutputStream();
            ops.write("你好我是客户端".getBytes());
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (ops != null)
                ops.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            try {
                if (socket != null)
                socket.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }




    }
    //服务端
    @Test
    public void server(){
        ServerSocket ss = null;
        Socket accept = null;
        InputStream ips = null;
        ByteArrayOutputStream baos = null;
        try {
            //1.创建服务器端的ServerSocket，指明自己的端口
            ss = new ServerSocket(8899);
            //2.调用accept()表示接收来自于服务端的socket
            accept = ss.accept();
            //3.获取输入流
            ips = accept.getInputStream();
            //4.读取
            baos = new ByteArrayOutputStream();
            byte[] buffer = new byte[5];
            int len;
            while((len = ips.read(buffer)) != -1){
                baos.write(buffer,0,len);
            }
            System.out.println(baos.toString());
            System.out.println("来自于："+accept.getInetAddress().getHostAddress());
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (ss != null)
                    ss.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            try {
                if (accept != null)
                    accept.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            try {
                if (ips != null)
                    ips.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            try {
                if (baos != null)
                    baos.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }


    }

    }

